package com.example.controller;

import com.example.entity.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class TestController {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping("/query")
    public List<Map<String, Object>> query(@RequestBody Query query) {
        String sql = query.getSql();
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    @PostMapping("/update")
    public int update(@RequestBody Query query) {
        String sql = query.getSql(); // update/insert/delete
        return jdbcTemplate.update(sql);
    }

    @GetMapping("/userList")
    public List<Map<String, Object>> getUserList() {
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    @GetMapping("/addUser")
    public String addUser() {

        String sql = "insert into user(id, name, password) values('1', 'zhangsan', 'qqqq')";
        jdbcTemplate.update(sql);

        return "add success";
    }

    /**
     * 可以通过占位符实现入参
     *
     * @param id
     * @return
     */
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id) {
        String sql = "update user set name =?, password = ? where id = " + id;

        // 封装占位符
        Object[] objects = new Object[2];
        objects[0] = "李四";
        objects[1] = "pppppp";

        jdbcTemplate.update(sql, objects);
        return "update success";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        String sql = "delete from user where id = ?";
        // int 类型也是一个object，所以这样传参也是可以的
        jdbcTemplate.update(sql, id);

        return "delete success";
    }

}
